package com.db.domain.bank;

import com.db.exceptions.BankException;

import java.io.Serializable;
import java.util.Date;

public class Bank implements Serializable {
    private Client[] clients = new Client[10];
    private int clientsNumber;
    private transient int listenersNumber;
    private transient ClientRegistrationListener[] listeners = new ClientRegistrationListener[10];

    public Bank() {
        addListener(new PrintClientListener());
        addListener(new DebugListener());
        addListener(new ClientRegistrationListener() {
            @Override
            public void onClientAdded(Client c) {
                System.out.println(c.getClientSalutation() + new Date().getTime());
            }
        });
    }

    public boolean addClient(Client client) throws BankException {
        if(clientsNumber == 10) return false;
        clients[clientsNumber++] = client;
        for (ClientRegistrationListener listener : listeners) {
            if (listener != null) {
                listener.onClientAdded(client);
            }
        }
        return true;
    }

    public Client[] getClients() {
        return clients;
    }

    public boolean addListener(ClientRegistrationListener listener) {
        if(listenersNumber == 10) {
            return false;
        }
        listeners[listenersNumber++] = listener;
        return true;
    }

    private class PrintClientListener implements ClientRegistrationListener {
        @Override
        public void onClientAdded(Client c) {
            System.out.println(c.getClientSalutation());
        }
    }

    private class DebugListener implements ClientRegistrationListener {
        @Override
        public void onClientAdded(Client c) {
            System.out.println(c.getClientSalutation() + " " + new Date());
        }
    }
}
